package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"home-manager/models/mysql"
	"home-manager/models/redis"
	"time"

	"home-manager/homerpc/homerpc"
	"home-manager/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HomeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHomeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HomeListLogic {
	return &HomeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 房屋列表方法
func (l *HomeListLogic) HomeList(in *homerpc.HomeListRequest) (*homerpc.HomeListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*homerpc.HomeList
	var err error

	key := fmt.Sprintf("home_list")

	result, _ := redis.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		list, err = mysql.HomeList(mysql.DB)
		if err != nil {
			return nil, errors.New("列表失败")
		}
		jsonData, _ := json.Marshal(list)
		redis.Rdb.Set(l.ctx, key, jsonData, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &homerpc.HomeListResponse{
		List: list,
	}, nil
}
